using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.XPath;

namespace AjGenesisStudio
{
    class Configs
    {
        public static void SetConfig(string name, string value)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(GetConfigFile());
            XmlNode node = doc.SelectSingleNode("//settings/setting[@name='" + name + "']/@value");
            if (node == null)
            {
                XmlElement el = (XmlElement)doc.SelectSingleNode("//settings");
                XmlElement el2 = doc.CreateElement("setting");
                XmlAttribute at = doc.CreateAttribute("name");
                at.Value = name;
                el2.Attributes.Append(at);
                at = doc.CreateAttribute("value");
                at.Value = value;
                el2.Attributes.Append(at);
                el.AppendChild(el2);
            }
            else
            {
                node.Value = value;
            }
            doc.Save(GetConfigFile());
        }

        public static string GetConfig(string name)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(GetConfigFile());
            XmlNode node = doc.SelectSingleNode("//settings/setting[@name='" + name + "']/@value");
            if (node == null)
                return string.Empty;
            else
                return node.Value.ToString();
        }

        public static string GetConfigFile()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.xml");
            if (!File.Exists(path))
            {
                XmlTextWriter writer = new XmlTextWriter(path, Encoding.Default);
                writer.WriteStartDocument();
                writer.WriteStartElement("config");
                writer.WriteStartElement("settings");
                writer.WriteEndElement();
                writer.WriteStartElement("filetypes");
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
            }
            return path;
        }

        public static XmlDocument GetConfigDocument()
        {
            XmlReader reader = new XmlTextReader(GetConfigFile());
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);
            reader.Close();
            return doc;
        }

    }
}
